package com.sxm.yiwei.pinche;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.R;
import com.sxm.yiwei.activitis.AppManager;
import com.sxm.yiwei.adapters.pinche.PhotoAdapter;
import com.sxm.yiwei.base.BaseActivity;
import com.sxm.yiwei.constant.Common;
import com.sxm.yiwei.constant.Constant;
import com.sxm.yiwei.tools.DialogMain;
import com.sxm.yiwei.views.BottomDialog;
import com.sxm.yiwei.views.MyGridView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

public class CarVerifyActivity extends BaseActivity implements View.OnClickListener,BottomDialog.OnBottomMenuItemClickListener {

    private RelativeLayout rl_back;
    private TextView tv_title;
    private TextView tv_private_car;
    private TextView tv_bus;
    private ImageView iv_drive_top;
    private ImageView iv_drive_bottom;
    private ImageView iv_drive_left;
    private ImageView iv_drive_right;
    private CheckBox checkBox;
    private Button btn_commit;
    private BottomDialog bottomDialog;
    private int photo_position=-1;
    private Uri photoURI;
    private Bitmap goodsImage;
    private String fileName;
    private int vehicle_type=Constant.PRIVATE_CAR;//1 私家车 2 大巴
    private ProgressDialog progressDialog;
    private MyGridView myGridView;
    private ArrayList<String> carList;
    private ArrayList<Bitmap> bitmapList;
    private ArrayList<String> verifyList;
    private PhotoAdapter photoAdapter;


    @Override
    public void setContentView() {
        setContentView(R.layout.activity_car_verify);
    }

    @Override
    public void initData() {
        tv_title.setText("车辆认证");
        carList =new ArrayList<>();
        bitmapList=new ArrayList<>();
        verifyList=new ArrayList<>();
        Bitmap carDefault= BitmapFactory.decodeResource(getResources(), R.mipmap.upload_car_default);
        bitmapList.add(carDefault);
        photoAdapter = new PhotoAdapter(this, bitmapList);
        myGridView.setAdapter(photoAdapter);
    }

    @Override
    public void initView() {
        rl_back = (RelativeLayout)findViewById(R.id.rl_back);
        tv_title = (TextView)findViewById(R.id.tv_title);
        tv_private_car = (TextView)findViewById(R.id.tv_private_car);
        tv_bus = (TextView)findViewById(R.id.tv_bus);
        iv_drive_top = (ImageView)findViewById(R.id.iv_drive_top);
        iv_drive_bottom = (ImageView)findViewById(R.id.iv_drive_bottom);
        iv_drive_left = (ImageView)findViewById(R.id.iv_drive_left);
        iv_drive_right = (ImageView)findViewById(R.id.iv_drive_right);
        myGridView = (MyGridView)findViewById(R.id.myGridView);
        checkBox = (CheckBox) findViewById(R.id.checkbox);
        btn_commit = (Button)findViewById(R.id.btn_commit);

        //初始化私家车为可选中状态
        tv_private_car.setTextColor(getResources().getColor(R.color.colorAb));
        tv_private_car.setBackgroundDrawable(getResources().getDrawable(R.drawable.pinche_style_textview_checked));
        tv_bus.setTextColor(getResources().getColor(R.color.colorbt));
        tv_bus.setBackgroundDrawable(getResources().getDrawable(R.drawable.pinche_style_textview_unchecked));
    }

    @Override
    public void initListener() {
        rl_back.setOnClickListener(this);
        tv_private_car.setOnClickListener(this);
        tv_bus.setOnClickListener(this);
        iv_drive_top.setOnClickListener(this);
        iv_drive_bottom.setOnClickListener(this);
        iv_drive_left.setOnClickListener(this);
        iv_drive_right.setOnClickListener(this);
        btn_commit.setOnClickListener(this);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!b){
                    btn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable.commit_order_btn_disable));
                    btn_commit.setEnabled(false);
                }else {
                    btn_commit.setBackgroundDrawable(getResources().getDrawable(R.drawable.commit_order_btn_enable));
                    btn_commit.setEnabled(true);
                }
            }
        });
        myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                photo_position=i;
                if (i==bitmapList.size()-1){//点击最后一张默认图片
                    showBottomDialog();

                }else {

                }
            }
        });

    }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.tv_private_car:
                vehicle_type=Constant.PRIVATE_CAR;
                tv_private_car.setTextColor(getResources().getColor(R.color.colorAb));
                tv_private_car.setBackgroundDrawable(getResources().getDrawable(R.drawable.pinche_style_textview_checked));
                tv_bus.setTextColor(getResources().getColor(R.color.colorbt));
                tv_bus.setBackgroundDrawable(getResources().getDrawable(R.drawable.pinche_style_textview_unchecked));
                break;
            case R.id.tv_bus:
                vehicle_type=Constant.BUS;
                tv_private_car.setTextColor(getResources().getColor(R.color.colorbt));
                tv_private_car.setBackgroundDrawable(getResources().getDrawable(R.drawable.pinche_style_textview_unchecked));
                tv_bus.setTextColor(getResources().getColor(R.color.colorAb));
                tv_bus.setBackgroundDrawable(getResources().getDrawable(R.drawable.pinche_style_textview_checked));
                break;
            case R.id.iv_drive_top:
                photo_position=Constant.DRIVE_UP;
                showBottomDialog();
                break;
            case R.id.iv_drive_bottom:
                photo_position=Constant.DRIVE_DOWN;
                showBottomDialog();
                break;
            case R.id.iv_drive_left:
                photo_position=Constant.GO_UP;
                showBottomDialog();
                break;
            case R.id.iv_drive_right:
                photo_position=Constant.GO_DOWN;
                showBottomDialog();
                break;
            case R.id.btn_commit:
                postVehicleVerify(vehicle_type);
                break;
        }
    }
    private void postVehicleVerify(int vehicle_type){
        progressDialog = ProgressDialog.show(this,"加载","正在加载中...");

        /*JSONObject object = new JSONObject();
        object.put("vehicleType",vehicle_type+"");
        JSONArray verifyArray = new JSONArray();
        JSONArray carArray = new JSONArray();
        for (int i = 0; i < verifyList.size(); i++) {

            verifyArray.add(new File(verifyList.get(i)));
            object.put("vehicleIdentity",verifyArray);//行驶证，驾驶证正反四张图片
        }
        for (int i = 0; i < carList.size(); i++) {
            carArray.add(new File(carList.get(i)));
            object.put("vehicleAvatar",carArray);//最少一张，最多四张车辆照片
        }
       *//* object.put("vehicleIdentity",verifyList);//行驶证，驾驶证正反四张图片
        object.put("vehicleAvatar",carList);//最少一张，最多四张车辆照片*/

        RequestParams params=  new RequestParams(Common.HOST+Common.VEHICLE_VERIFICATION);
        Log.d("getHead",getHeadInfo().getToken()+"getHeadInfo  "+getHeadInfo().getAppId()+"getUserId  "+getHeadInfo().getUserId());
        params.addHeader("Content-Type","multipart/form-data");
        params.addHeader("token",getHeadInfo().getToken());
        params.addHeader("appId",getHeadInfo().getAppId());
        params.addHeader("userId",getHeadInfo().getUserId());
        params.addBodyParameter("vehicleType",vehicle_type+"");
        for (int i = 0; i < verifyList.size(); i++) {
            params.addBodyParameter("vehicleIdentity",new File(verifyList.get(i)));//行驶证，驾驶证正反四张图片
        }
        for (int i = 0; i < carList.size(); i++) {
            params.addBodyParameter("vehicleAvatar",new File(carList.get(i)));//最少一张，最多四张车辆照片
        }
        Log.d("认证图片",verifyList.toString());
        Log.d("车辆图片",carList.toString());

        params.setMultipart(true);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();

                Log.d("tag", "onSuccess: 车辆认证--"+result);
                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                if (obj.getIntValue("status")==1){
                    AlertDialog.Builder builder = null;
                    builder = new AlertDialog.Builder(AppManager.getAppManager().currentActivity());
                    builder.setCancelable(true);
                    View view = LayoutInflater.from(AppManager.getAppManager().currentActivity()).inflate(R.layout.tip_dialog, null);
                    builder.setView(view);
                    TextView know = (TextView) view.findViewById(R.id.know);
                    TextView message = (TextView) view.findViewById(R.id.dialog_text);
                    know.setText("知道了");
                    message.setText("您的车辆认证已提交，请等待我们的审核！");
                    final AlertDialog dialog = builder.create();
                    know.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                            CarVerifyActivity.this.finish();
                        }
                    });
                    dialog.show();
                }else {
                    showToast("车辆审核没有提交成功");
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                showToast("onError");
                Log.d("tag", "onError: 车辆认证--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    private void showBottomDialog() {
        bottomDialog = new BottomDialog(this, R.layout.dialog_bottom_layout, new int[]{R.id.pick_photo_camera, R.id.pick_photo_album});
        bottomDialog.setOnBottomMenuItemClickListener(this);
        bottomDialog.show();
        TextView pick_photo_camera = (TextView) bottomDialog.findViewById(R.id.pick_photo_camera);
        TextView pick_photo_cancel = (TextView) bottomDialog.findViewById(R.id.pick_photo_cancel);
        TextView pick_photo_album = (TextView) bottomDialog.findViewById(R.id.pick_photo_album);

    }

    @Override
    public void onBottomMenuItemClick(BottomDialog dialog, View view) {
        switch (view.getId()){
            case R.id.pick_photo_camera:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //如果没有授权，则请求授权
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                } else {
                    //有授权，直接开启摄像头
                    callCamera();
                }
                break;
            case R.id.pick_photo_album:
                callGallery();
                break;
            case R.id.pick_photo_cancel:
                dialog.cancel();
                break;
        }
    }
    public void callGallery() {
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        startActivityForResult(intent, 1);
    }
    private void callCamera(){
        File file = new File(Environment.getExternalStorageDirectory(),
                "/goods_image" + ".jpg");
        if (Build.VERSION.SDK_INT >= 24) {
            photoURI = FileProvider.getUriForFile(this,
                    "com.sxm.yiwei.provider",
                    file);
        }else {
            photoURI= Uri.fromFile(file);
        }

        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= 24) {
            intent2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent2.putExtra(MediaStore.EXTRA_OUTPUT,photoURI );
        startActivityForResult(intent2, 2);//采用ForResult打开
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //判断请求码
        if (requestCode == Constant.MY_PERMISSIONS_REQUEST_CALL_CAMERA) {
            //grantResults授权结果
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //成功，开启摄像头
                callCamera();
            } else {
                //授权失败
                Toast.makeText(this, "没有授权无法进行该操作！", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //1.从相册中选择
            case 1:
                if (resultCode == RESULT_OK) {

                    cropPhoto(data.getData());//裁剪图片
                }

                break;
            //2，拍照
            case 2:

                if (resultCode == RESULT_OK) {

                    cropPhoto(photoURI);//裁剪图片

                }
                break;
            case 3:

                if (data != null) {
                    Bundle extras = data.getExtras();
                    goodsImage = extras.getParcelable("data");
                    if(goodsImage!=null){
                        setPicToView(goodsImage);//保存在SD卡中
                        if (photo_position==Constant.DRIVE_UP){
                            iv_drive_top.setImageBitmap(goodsImage);

                        }else if (photo_position==Constant.DRIVE_DOWN){
                            iv_drive_bottom.setImageBitmap(goodsImage);

                        }else if (photo_position==Constant.GO_UP){
                            iv_drive_left.setImageBitmap(goodsImage);

                        }else if (photo_position==Constant.GO_DOWN){
                            iv_drive_right.setImageBitmap(goodsImage);

                        }else {
                            bitmapList.add(0,goodsImage);
                            photoAdapter.notifyDataSetChanged();
                        }

                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);

    }
    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(Constant.IMAGE_PATH);
        file.mkdirs();// 创建文件夹
        fileName = Constant.IMAGE_PATH + "goods_image"+photo_position+".jpg";//图片名字
        if (photo_position==Constant.GO_DOWN||photo_position==Constant.GO_UP||photo_position==Constant.DRIVE_UP||photo_position==Constant.DRIVE_DOWN){
            //证件图片
            verifyList.add(fileName);
        }else {
            //车辆图片
            carList.add(fileName);

        }
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
